package com.example.jt_manager_service;

import com.example.jt_common.RedisService;
import com.example.jt_common.vo.ItemParams;
import com.example.jt_manager_mapper.*;
import com.example.jt_manager_pojo.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    ItemCatMapper itemCatMapper;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemDescMapper itemDescMapper;

    @Autowired
    ItemParamMapper itemParamMapper;

    @Autowired
    RedisService redisService;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    ItemParamItemMapper itemParamItemMapper;


//    SELECT * FROM tb_item_cat WHERE STATUS=1 AND parent_id=0
//    ORDER BY parent_id,sort_order;
    @Override
    public List<ItemCat> queryGoodsCategory(long id) {

        //先去redis中查找是否含有该数据
        //如果有，直接返回redis中的数据
        //如果没有，再执行数据库查询操作，并将该数据放入redis缓存中

        String ITEM_CAT_KEY = "ITEM_CAT_"+id;
        String reslut = redisService.getDataByKey(ITEM_CAT_KEY);
        //redis中无数据
        if (StringUtils.isEmpty(reslut)){
            ItemCatExample itemCatExample= new ItemCatExample();
            itemCatExample.setOrderByClause("parent_id");
            itemCatExample.setOrderByClause("sort_order");
            itemCatExample.createCriteria().andStatusEqualTo(1).andParentIdEqualTo(id);
            List<ItemCat> itemCats = itemCatMapper.selectByExample(itemCatExample);

            //向redis中存储一份数据
            try {
                String jsonItemCats = objectMapper.writeValueAsString(itemCats);
                redisService.setData(ITEM_CAT_KEY,jsonItemCats);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return itemCats;
        }else {
            //redis中有数据，得到json
            String jsonResult = redisService.getDataByKey(ITEM_CAT_KEY);
            //解析json
            JavaType javaType=objectMapper.getTypeFactory().constructParametricType(ArrayList.class,ItemCat.class);
            try {
                List<ItemCat> itemCats = objectMapper.readValue(jsonResult,javaType);
                return itemCats;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;

        }

    }

    @Override
    public void addGood(Item item,String desc) {
        itemMapper.insertSelective(item);
        addGoodsDesc(item.getId(),desc);
    }

    @Override
    public void updateGood(Item item, String desc) {
        itemMapper.updateByPrimaryKeySelective(item);
        try{
            updateGoodsDesc(item.getId(),desc);
        }catch (Exception e){
            //如果原来商品描述就不存在，则执行插入操作
            addGoodsDesc(item.getId(),desc);
        }
    }

    @Override
    public void addGoodsDesc(long id, String desc) {
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(id);
        itemDesc.setItemDesc(desc);
        itemDesc.setCreated(new Date());
        itemDesc.setUpdated(new Date());
        itemDescMapper.insertSelective(itemDesc);
    }

    @Override
    public void updateGoodsDesc(long id, String desc) {
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(id);
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(new Date());
        itemDescMapper.updateByPrimaryKey(itemDesc);
    }

    @Override
    public PageInfo<Item> queryGoodsByPage(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
//        ItemExample itemExample = new ItemExample();
        List<Item> items = itemMapper.selectAll();
        PageInfo<Item> pageInfo = new PageInfo<>(items);
        return pageInfo;
    }

    @Override
    public int deleteGoods(List<Long> ids) {
        ItemExample itemExample = new ItemExample();
        itemExample.createCriteria().andIdIn(ids);
        return itemMapper.deleteByExample(itemExample);
    }

    @Override
    public ItemDesc queryItemDescById(long id) {
        ItemDescExample itemDescExample = new ItemDescExample();
        itemDescExample.createCriteria().andItemIdEqualTo(id);
        List<ItemDesc> list = itemDescMapper.selectByExample(itemDescExample);
        if(list.size()!=0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public int itemInstock(List<Long> ids) {
        Item item = new Item();
        item.setStatus(Byte.valueOf("2"));
        ItemExample itemExample = new ItemExample();
        itemExample.createCriteria().andIdIn(ids);
        return itemMapper.updateByExampleSelective(item,itemExample);
    }

    @Override
    public int itemReshelf(List<Long> ids) {
        Item item = new Item();
        item.setStatus(Byte.valueOf("1"));
        ItemExample itemExample = new ItemExample();
        itemExample.createCriteria().andIdIn(ids);
        return itemMapper.updateByExampleSelective(item,itemExample);
    }

    @Override
    public Item queryItemByID(long id) {
        Item item = itemMapper.selectByPrimaryKey(id);
        String images = item.getImage();
        String[] imageArray = images.split(",");
        item.setImageArray(imageArray);
        return item;
    }

//    @Override
//    public PageInfo<ItemParam> queryItemParamByPage(int page, int size) {
//        PageHelper.startPage(page, size);
//        ItemParamExample example = new ItemParamExample();
//        List<ItemParam> params = itemParamMapper.selectByExample(example);
//        PageInfo<ItemParam> pageInfo = new PageInfo<>(params);
//        return pageInfo;
//    }

    @Override
    public PageInfo<ItemParam> queryItemParamByPage(int page, int size) {
        PageHelper.startPage(page, size);
        List<ItemParam> params = itemParamMapper.selectAll();
        PageInfo<ItemParam> pageInfo = new PageInfo<>(params);
        return pageInfo;
    }

    @Override
    public int deleteParamByIds(List<Long> ids) {
        ItemParamExample example = new ItemParamExample();
        example.createCriteria().andIdIn(ids);
        return itemParamMapper.deleteByExample(example);
    }

    @Override
    public int isExistParamById(long id) {
        ItemParamExample itemParamExample = new ItemParamExample();
        itemParamExample.createCriteria().andItemCatIdEqualTo(id);
        return itemParamMapper.selectByExample(itemParamExample).size();
    }

    @Override
    public List<ItemParams> queryParamById(long id) {
        ItemParamItemExample itemParamItemExample = new ItemParamItemExample();
        itemParamItemExample.createCriteria().andItemIdEqualTo(id);
        List<ItemParamItem> itemParamItems = itemParamItemMapper.selectByExample(itemParamItemExample);
        if (itemParamItems.size()!=0){
            ItemParamItem itemParam = itemParamItems.get(0);
            String jsonStringParamData = itemParam.getParamData();

            JavaType javaType=objectMapper.getTypeFactory().constructParametricType(ArrayList.class, ItemParams.class);
            try {
                List<ItemParams> param = objectMapper.readValue(jsonStringParamData,javaType);
                return param;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public int insertParam(ItemParam itemParam) {
        return itemParamMapper.insertSelective(itemParam);
    }

}
